﻿@{
    ViewData["Title"] = "RoomNumberType";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>房号管理</h1>
<div class="layui-form-item">
    <label class="layui-form-label">房号</label>
    <div class="layui-input-inline">
        <input type="text" id="txtroomnum" placeholder="请输入房号" autocomplete="off" class="layui-input">

    </div>

    <select name="conditionSelect" id="conditionSelect" lay-filter="conditionFilter">
        <option value=0 selected>请选择</option>
        <option value=1>上架</option>
        <option value=0>下架</option>
    </select>

    <select name="roomIds" id="roomIds" lay-filter="房型" lay-search="required">
        <option value="0" selected>请选择</option>
    </select>

    <button class="layui-btn" lay-submit lay-filter="demoTable" lay-event="myBtn">查询</button>
    <button type="button" class="layui-btn layui-bg-blue" id="addNumber">新增房号</button>
    <button type="button" class="layui-btn layui-bg-blue" id="piliangdaoru">批量导入(未完成)</button>
</div>
@* 显示房号 *@
<table class="layui-table" id="demoTable" lay-filter="demoTable">
    <tbody>
        <!-- 这里是动态生成的数据 -->
    </tbody>
</table>
@* //房号操作列 *@
<script type="text/html" id="buttonTemplate">
    <button class="layui-btn layui-btn-xs" lay-event="editFunction">编辑</button>
    <button class="layui-btn layui-btn-xs" lay-event="lastList">下架</button>
    <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="deleteFunction">删除</button>
</script>
@* 房号添加弹出框 *@
<div id="roomNumberAdd" style="display:none">
    <form class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">选择房型</label>
            <div class="layui-input-block" style="width:20%;height:5%">
                <select id="roomId" name="roomId" lay-filter="roomId" lay-search="required">
                 
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">  <span style="color:red">*</span>房号</label>
            <div class="layui-input-block">
                <input type="text" name="roomNumber" id="roomNumber" lay-verify="required" placeholder="房号">
            </div>
        </div>

        <div class="layui-form-item" style="display:none">
            <label class="layui-form-label">房号ID</label>
            <div class="layui-input-block">
                <input type="text" name="numberId" id="numberId" placeholder="房号">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">  <span style="color:red">*</span>排序</label>
            <div class="layui-input-block">
                <input type="text" name="orderByNumber" id="orderByNumber" lay-verify="required" placeholder="排序">
                数字越大排越前
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">  <span style="color:red">*</span>备注</label>
            <div class="layui-input-block">
                <input type="text" name="remark" id="remark" lay-verify="required" placeholder="备注不超过九个字">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="reset" class="layui-btn layui-btn-primary">取消</button>
                <button class="layui-btn" lay-submit lay-filter="submitForm">添加</button>
                <button class="layui-btn" lay-submit lay-filter="EditForm">修改</button>
            </div>
        </div>
    </form>
</div>
<div id="Fileupload" style="display:none;width:30%;height:30%">
    <input type="file" id="fileUpload" name="fileUpload">
    <br />
    请先下载房号导入模版，并按照提示填写
    <br />
    文件最大2M,支持扩展名:xls,xlsx
    <br />
    <button class="layui-btn" id="downloadBtn">下载房号导入模版</button>
</div>
<div id="demo-laypage-layout-1"></div>
<html>
<body>
    <script>
        layui.use(['table', 'jquery', 'layer', 'form', 'laypage'], function () {

            var tatolcount = 0;
            var table = layui.table;
            var $ = layui.jquery;
            var form = layui.form;
            var layer = layui.layer;
            var laypage = layui.laypage;
            var statueid = form.val('conditionFilter');
            //form.render('select');
            var from = {
                statueid: $("#conditionSelect").val(),
                roomId: $("#roomIds").val(),
                roomnumber: $("#txtroomnum").val()

            }
            //显示
            function show() {
                console.log(from.field)
                $.ajax({
                    url: 'http://localhost:5174/api/RoomType/GetRoomNumber',
                    type: 'post',
                    contentType: "application/json",
                    data: JSON.stringify(from),
                    headers: {
                        "Authorization": "Bearer " + localStorage.getItem('token')
                    },
                    async: true,
                    success: function (res) {
                        table.render({
                            elem: '#demoTable',
                            data: res.data,
                            cols: [[
                                { type: 'checkbox' },
                                { field: 'roomName', title: '房型名称' },
                                { field: 'roomNumber', title: '房号' },
                                { field: 'orderByNumber', title: '排序', sort: true },
                                { field: 'remark', title: '备注' },
                                {
                                    field: 'state', title: '状态', templet: function (d) {
                                        // 根据数据中的某个条件使用三目运算符返回不同的值
                                        return d.state == 1 ? '上架' : '下架';
                                    }
                                },
                                { toolbar: '#buttonTemplate', title: '操作' }
                            ]],
                            //page: true
                        });
                    },
                    error: function (error) {
                        console.error(error);

                    }
                })
            }
            show()
            $(document).on('click', '[lay-event="myBtn"]', function () {
                var data = {
                    statueid: $("#conditionSelect").val(),
                    roomId: $("#roomIds").val(),
                    roomnumber: $("#txtroomnum").val()
                }
                console.log(data)
                // 处理点击事件的逻辑
                $.ajax({
                    url: 'http://localhost:5174/api/RoomType/GetRoomNumber',
                    type: 'post',
                    contentType: "application/json",
                    data: JSON.stringify(data),
                    headers: {
                        "Authorization": "Bearer " + localStorage.getItem('token')
                    },
                    async: true,
                    success: function (res) {
                        table.render({
                            elem: '#demoTable',
                            data: res.data,
                            cols: [[
                                { type: 'checkbox' },
                                { field: 'roomName', title: '房型名称' },
                                { field: 'roomNumber', title: '房号' },
                                { field: 'orderByNumber', title: '排序', sort: true },
                                { field: 'remark', title: '备注' },
                                {
                                    field: 'state', title: '状态', templet: function (d) {
                                        // 根据数据中的某个条件使用三目运算符返回不同的值
                                        return d.state == 1 ? '上架' : '下架';
                                    }
                                },
                                { toolbar: '#buttonTemplate', title: '操作' }


                            ]],
                            page: true
                        });
                    },
                    error: function (error) {
                        console.error(error);

                    }
                })
            });

            // table.render({
            //     elem: 'demoTable',
            //     url: 'http://localhost:5174/api/RoomType/GetRoom',
            //     method:'post',
            //     cellMinWidth:80,
            //     cols: [[
            //         { type: 'checkbox' },
            //         { field: 'roomName', title: '房型名称' },
            //         { field: 'price', title: '门市价（元）' },
            //         { field: 'lodgingToll', title: '房间数量', },
            //         { field: 'roomDesc', title: '排序' }
            //     ]],
            // })


            //反选
            // 监听全选复选框
            form.on('checkbox(selectAll)', function (data) {
                var isChecked = data.elem.checked;
                var checkboxes = document.querySelectorAll('#dataTable tbody input[type="checkbox"]');
                checkboxes.forEach(function (checkbox) {
                    checkbox.checked = isChecked;
                });
            });

        
            //弹出层 添加房号
            $(".layui-btn").click(function () {
                var id = $(this).attr('id');
              
                if (id === "addNumber") {
                    console.log("点击新增房号");
                    layer.open({
                        type: 1,
                        area: ['630px', '360px'],
                        shade: false, // 不显示遮罩
                        content: $('#roomNumberAdd'), // 捕获的元素
                        end: function (iayero, index) {
                            // layer.msg('关闭后的回调', {icon:6});

                        }
                    });
                
                }
            });

            //批量导入
            $(".layui-btn").click(function () {
                var id = $(this).attr('id');
                if (id === "piliangdaoru") {
                    layer.open({
                        type: 1,
                        area: ['630px', '360px'],
                        shade: false, // 不显示遮罩
                        content: $('#Fileupload'), // 捕获的元素
                        end: function () {
                            // layer.msg('关闭后的回调', {icon:6});
                        }
                    });
                }
            });

            //excel导出
            $(".layui-btn").click(function () {
                var id = $(this).attr('id');
                if (id === "downloadBtn") {
                    console.log("excel模版")
                    $.ajax({
                        url: 'http://localhost:5174/api/RoomType/GetExcel',  // 替换为实际的控制器和方法路径
                        type: 'POST',
                        success: function (response) {
                            // 处理下载
                            var blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

                            // 创建下载链接
                            var link = document.createElement('a');
                            link.href = window.URL.createObjectURL(blob);
                            link.download = '房号批量模版.xlsx';

                            // 模拟点击下载链接
                            link.click();
                        },
                        error: function (xhr, status, error) {
                            console.error(error);
                        }
                    });
                }

            })
            var defaultOption = document.createElement('option');
            defaultOption.text = '请选择';
            defaultOption.value = '';
            //绑定下拉框
            function getRoomType() {     
                $.ajax({
                    url: 'http://localhost:5174/api/RoomType/GetAllRoom',
                    type: 'GET',
                    dataType: 'json',
                    success: function (response) {
                        var form = layui.form;
                        form.render('select');
                        var select = $('#roomIds');
                        
                        // 首先添加"请选择"选项到下拉框的开头
                        select.prepend($('<option>', {
                            value: '',  // 可根据实际情况设置值
                            text: '请选择'
                        }));
                        select.find('option').not(':first').remove(); // 清空原有的除"请选择"外的选项
                        $.each(response.data, function (index, item) {
                            select.append($('<option>', {
                                value: item.roomId,
                                text: item.roomName
                            }));
                        });
                        form.render('select'); // 重新渲染

                    },
                    error: function (error) {
                        console.error('请求失败：', error);
                    }
                });
            }
            $.ajax({
                url: 'http://localhost:5174/api/RoomType/GetAllRoom',
                type: 'GET',
                dataType: 'json',
                success: function (response) {
                    var form = layui.form;
                    form.render('select');
                    var select = $('#roomId');

                    // 首先添加"请选择"选项到下拉框的开头
                    select.prepend($('<option>', {
                        value: '',  // 可根据实际情况设置值
                        text: '请选择'
                    }));
                    select.find('option').not(':first').remove(); // 清空原有的除"请选择"外的选项
                    $.each(response.data, function (index, item) {
                        select.append($('<option>', {
                            value: item.roomId,
                            text: item.roomName
                        }));
                    });
                    form.render('select'); // 重新渲染

                },
                error: function (error) {
                    console.error('请求失败：', error);
                }
            });
            getRoomType();

            //添加房号
            form.on('submit(submitForm)', function (data) {
             
                console.log("添加房号获取的数据"+data)
                data.elem.disabled = true;//防止重复提交
                $.ajax({
                    url: 'http://localhost:5174/api/RoomType/AddRoomNumber',
                    type: 'post',
                    contentType: "application/json",
                    data: JSON.stringify(data.field),
                    success: function (res) {
                        // 添加成功后的操作
                        if (res.code > 0) {
                            layer.msg("添加成功");
                            show()
                        }
                    }
                });
                return false;
            });
            //修改房号
            form.on('submit(EditForm)', function (data) {
                $.ajax({
                    url: 'http://localhost:5174/api/RoomType/UpdateROomNUmber',
                    type: 'post',
                    contentType: "application/json",
                    data: JSON.stringify(data.field),
                    success: function (res) {
                        // 添加成功后的操作
                        if (res.code > 0) {
                            layer.msg("修改成功");
                            show()
                        }
                    }
                });
                return false;
            })
            table.on('tool()', function (obj) {
                var data = obj.data; // 获取当前行数demoTable据
                var layEvent = obj.event; // 获取 lay-event 对应的值
                var numberid = data.numberId;
                //删除所用ID
                var maArrayid = [];
                maArrayid.push(data.numberId)
                console.log(data)
                if (layEvent === 'editFunction') {
                    // $.ajax({
                    //     url: 'http://localhost:5174/api/RoomType/ByroomNumberIdGetRoomNumber',  // 替换成实际的接口地址
                    //     type: 'GET',
                    //     data: { id: data.numberId },  // 传递的参数
                    //     success: function (data) {
                    //         // 将数据填充到表单中
                    //         console.log("反填" + data.data.)

                    //         document.getElementById('numberId').value = data.data.numberId;
                    //         document.getElementById('roomNumber').value = data.data.roomNumber;
                    //         document.getElementById('orderByNumber').value = data.data.orderByNumber;
                    //         document.getElementById('remark').value = data.data.remark;
                    //        // document.getElementById('roomId').value = data.data.roomId;
                    //         var select = $('#roomId'); // 'popupSelect' 为弹出层下拉框的 ID
                    //         select.empty(); // 清空原有选项（如果需要）
                    //         for (var i = 0; i < data.data.length; i++) {
                    //             var jsonobj = data.data[i];
                    //             select.append("<option value='" + jsonobj.roomId + "'>" + jsonobj.roomName + "</option>");
                    //         }
                    //         // 重新渲染下拉框
                    //         form.render("select");
                    //     },
                    //     error: function (xhr, status, error) {
                    //         console.error('Error fetching user data:', error);
                    //         // 处理错误情况
                    //     }
                    // });


                    document.getElementById('numberId').value = data.numberId;
                    document.getElementById('roomNumber').value = data.roomNumber;
                    document.getElementById('orderByNumber').value = data.orderByNumber;
                    document.getElementById('remark').value = data.remark;
                    getRoomType();
                    document.getElementById('roomId').value = data.roomId;

                    layer.open({
                        title: '编辑 - id:' + data.numberId,
                        type: 1,
                        shade: false, // 不显示遮罩
                        area: ['80%', '80%'],
                        content: $('#roomNumberAdd'),
                        end: function () {
                            // layer.msg('关闭后的回调', {icon:6});
                        }

                    });
                }
                else if (layEvent === 'deleteFunction') {
                    console.log("执行删除方法")
                    $.ajax({
                        url: 'http://localhost:5174/api/RoomType/DeleteRoomNumber',
                        type: 'post',
                        contentType: "application/json",
                        data: JSON.stringify({ ids: maArrayid }),
                        headers: {
                            "Authorization": "Bearer " + localStorage.getItem('token')
                        },
                        success: function (res) {
                            if (res.code > 0) {
                                layer.msg("删除成功");
                                show()
                            }

                            // 删除成功后的操作
                        }
                    });
                }
                else if (layEvent === 'lastList') {
                    console.log("下架" + numberid)
                    $.ajax({
                        url: 'http://localhost:5174/api/RoomType/UpdateStateshelves',
                        type: 'get',
                        data: { id: numberid },
                        headers: {
                            "Authorization": "Bearer " + localStorage.getItem('token')
                        },
                        success: function (res) {
                            if (res.code > 0) {
                                layer.msg("下架成功");
                                show()
                            }

                            // 删除成功后的操作z
                        }
                    });
                }

            });







            //表单校验
            form.verify({
                remark: [/^.{0,9}$/, '不能超过9个字'],
                roomNumber: [/^.{0,9}$/, '不能超过9个字'],
                //roomImage: [/^\S+$/, '必填项不能为空']
            });
        });
    </script>

</body>
</html>
